let Vue;


class CVueRouter {
    constructor(options) {
        this.$options = options;
        Vue.util.defineReactive(this, "current", window.location.hash.slice(1));
        window.addEventListener("hashchange", () => {
            this.current = window.location.hash.slice(1);
        })
    }
}

CVueRouter.install = function (_Vue) {
    Vue = _Vue;
    Vue.mixin({
        beforeCreate() {
            if (this.$options.router) {//判断组件实例是不是为根实例
                Vue.prototype.$router = this.$options.router;
            }
        }
    })
    Vue.component("router-link", {
        props: {
            to: {//接受一个to 跳转的地址
                type: String,
                required: true
            },
            tag:{
                type: String,
                default:"a"
            }
        },
        render(h) {
            const _this = this
            return h(this.tag, {
                on: {
                    click(e) {
                        e.preventDefault();
                        window.location.hash = _this.to;
                    }
                }
            }, this.$slots.default)
        }
    })
    Vue.component("router-view", {
        render(h) {
            let component = null;
            this.$router.$options.routes.forEach(async item => {
                if (item.path == this.$router.current) {
                    if (typeof item.component == "function") { //支持路由组件懒加载
                        component = item.component;
                        component = await item.component();
                    } else {
                        component = item.component;
                    }

                }
            })
            return h(component)
        }
    })
}

export default CVueRouter;